package com.xuetang9.t9.hotel.mapper.sql.impl;

import com.xuetang9.t9.hotel.mapper.condition.ICondition;
import com.xuetang9.t9.hotel.mapper.condition.impl.CommodityTypeCondition;
import com.xuetang9.t9.hotel.mapper.condition.impl.EConsumptionCondition;
import com.xuetang9.t9.hotel.mapper.sql.IMapperSql;
import org.apache.ibatis.jdbc.SQL;

import java.util.Map;

public class EConsumptionMapperSql implements IMapperSql {
    @Override
    public String selectByAll(Map map) {
        ICondition key = (ICondition) map.get("key");
        return getCondition(key,"*",true);
    }

    @Override
    public String selectByCount(Map map) {
        ICondition key = (ICondition) map.get("key");
        return getCondition(key,"COUNT(*)",false);
    }

    private String getCondition(ICondition condition, String select, boolean isPage) {
        SQL sql = new SQL();
        sql.SELECT(select).FROM("e_consumption");
        if(condition == null){
            return sql.toString();
        }
        EConsumptionCondition key = null;
        if(condition instanceof EConsumptionCondition){
            key = (EConsumptionCondition) condition;
        }else{
            throw  new RuntimeException("condition type Don't match");
        }
        if(null != key){
            if(null != key.getId()){
                sql.WHERE("id LIKE '%"+key.getId()+"%'");
            }
            if(key.getOrderType() != null && !key.getOrderType().isEmpty() && !key.getOrderType().equals("全部")){
                sql.WHERE("orderType = '"+key.getOrderType()+"'");
            }
            if(key.getState() != null && !key.getState().isEmpty() && !key.getState().equals("全部")){
                sql.WHERE("state = '"+key.getState()+"'");
            }
            if(key.getFoot() != null && !key.getFoot().isEmpty()){
                sql.WHERE("id IN(SELECT e_consfood.id FROM e_consfood\n" +
                        "LEFT JOIN e_food\n" +
                        "ON e_consfood.foodId = e_food.id\n" +
                        "WHERE e_food.`name` LIKE '%"+key.getFoot()+"%')");
            }
            if(null != key.getOrderTimebegin() && !key.getOrderTimebegin().isEmpty()
            && null != key.getOrderTimeend() && !key.getOrderTimeend().isEmpty()){
                sql.WHERE( "orderTime BETWEEN '"+key.getOrderTimebegin()+"'AND'"
                        +key.getOrderTimeend()+"'OR orderTime BETWEEN '"+key.getOrderTimebegin()+"'AND'" +key.getOrderTimebegin()+"'");
            }
            if(key.judge()  && isPage){
                sql.LIMIT(key.getCurrPage()+","+key.getPageSize());
            }
        }
        return sql.toString();
    }
}
